<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import downloadManager from '@/utils/download.js'
import { getImageById } from '@/api/index.js'

const route = useRoute()
const router = useRouter()

// 下载状态
const isCached = ref(false)
const downloading = ref(false)

// 全局缓存引用（从Home.vue共享）
const globalCache = window.globalCache || new Map()

// 缓存管理函数
const getCachedBlob = (url) => {
  const cached = globalCache.get(url)
  if (cached && Date.now() - cached.timestamp < 600000) { // 10分钟缓存
    return cached.blob
  }
  // 清理过期缓存
  if (cached) {
    globalCache.delete(url)
  }
  return null
}

const setCachedBlob = (url, blob) => {
  // 清理旧缓存，保持缓存大小在合理范围内
  if (globalCache.size > 50) {
    const oldestKey = globalCache.keys().next().value
    globalCache.delete(oldestKey)
  }
  
  globalCache.set(url, {
    blob,
    timestamp: Date.now()
  })
}

// 清理所有缓存
const clearCache = () => {
  globalCache.clear()
}

// 壁纸数据
const wallpaper = ref({
  id: null,
  title: '',
  resolution: '4K (3840x2160)',
  downloads: 0,
  likes: 0,
  liked: false,
  image: '',
  description: '',
  classify: '',
  tags: []
})

// 加载状态
const loading = ref(false)

// 判断是否为视频格式（已禁用视频功能）
const isVideo = (url) => {
  return false // 禁用视频功能
}

// 预加载图片文件
const preloadFile = async (url) => {
  if (getCachedBlob(url)) return // 已缓存
  
  try {
    const response = await fetch(url, {
      method: 'GET',
      mode: 'cors',
      credentials: 'omit',
      headers: {
        'Accept': 'image/*',
        'Cache-Control': 'max-age=600' // 10分钟缓存
      }
    })
    
    if (response.ok) {
      const blob = await response.blob()
      setCachedBlob(url, blob)
      isCached.value = true
    }
  } catch (error) {
    // 预加载失败，静默处理
  }
}

// 分片下载图片（适用于大文件）
const downloadInChunks = async (url, onProgress) => {
  const response = await fetch(url, {
    method: 'GET',
    mode: 'cors',
    credentials: 'omit',
    headers: {
      'Accept': 'image/*',
      'Cache-Control': 'max-age=300'
    }
  })
  
  if (!response.ok) {
    throw new Error(`网络请求失败: ${response.status}`)
  }
  
  const contentLength = response.headers.get('content-length')
  const total = contentLength ? parseInt(contentLength) : 0
  let loaded = 0
  
  const reader = response.body.getReader()
  const chunks = []
  
  while (true) {
    const { done, value } = await reader.read()
    
    if (done) break
    
    chunks.push(value)
    loaded += value.length
    
    if (onProgress && total > 0) {
      onProgress(loaded, total)
    }
  }
  
  return new Blob(chunks)
}

// 根据ID获取壁纸详情
const fetchWallpaperById = async (id) => {
  if (!id) {
    ElMessage.error('图片ID不能为空')
    return
  }
  
  loading.value = true
  
  try {
    const response = await getImageById(id)
    
    if (response.code === 200 && response.data) {
      const imageData = response.data
      
      // 更新壁纸数据
      wallpaper.value = {
        id: imageData.id,
        title: imageData.name || '壁纸',
        resolution: '4K (3840x2160)',
        downloads: imageData.download || 0,
        likes: imageData.heat || 0,
        liked: false,
        image: imageData.url,
        description: `这是一张精美的${imageData.name}壁纸，展现了独特的艺术魅力。`,
        classify: imageData.classify || '未分类',
        tags: imageData.classify ? [imageData.classify, '4K'] : ['未分类', '4K']
      }
      
      // 预加载图片
      if (wallpaper.value.image) {
        preloadFile(wallpaper.value.image)
      }
      
    } else {
      ElMessage.error(response.msg || '获取图片详情失败')
    }
    
  } catch (error) {
    console.error('获取图片详情失败:', error)
    ElMessage.error('获取图片详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}







// 使用下载管理器进行下载
const enhancedDownload = async () => {
  if (downloading.value) return
  
  downloading.value = true
  
  try {
    const fileUrl = wallpaper.value.image
    const fileName = downloadManager.getFileName(fileUrl, wallpaper.value.title)
    
    ElMessage.info('正在准备下载...')
    
    await downloadManager.download(fileUrl, fileName, {
      timeout: 30000,
      disableCache: true // 禁用缓存以避免卡顿
    })
    
    ElMessage.success(`开始下载: ${wallpaper.value.title}`)
    
  } catch (error) {
    console.error('下载失败:', error)
    
    // 更详细的错误信息
    let errorMessage = '下载失败'
    if (error.message.includes('Failed to fetch') || error.message.includes('网络错误')) {
      errorMessage = '网络请求失败，可能是图片地址问题或网络连接问题'
    } else if (error.message.includes('timeout')) {
      errorMessage = '下载超时，请检查网络连接'
    } else if (error.message.includes('CORS') || error.message.includes('Access-Control-Allow-Origin')) {
      errorMessage = '跨域访问被阻止，正在尝试其他下载方式...'
    } else if (error.message.includes('所有下载方法都失败了')) {
      errorMessage = '所有下载方式都失败了，请稍后重试或联系管理员'
    } else {
      errorMessage = `下载失败: ${error.message}`
    }
    
    ElMessage.error(errorMessage)
  } finally {
    downloading.value = false
  }
}




// 图片错误处理
const handleImageError = (event) => {
  event.target.src = '/placeholder-image.jpg'
}

// 重试加载
const retryLoad = () => {
  const wallpaperId = route.params.id
  if (wallpaperId) {
    fetchWallpaperById(wallpaperId)
  }
}

onMounted(() => {
  // 根据路由参数加载壁纸数据
  const wallpaperId = route.params.id
  
  // 根据ID获取壁纸详情
  if (wallpaperId) {
    fetchWallpaperById(wallpaperId)
  } else {
    ElMessage.error('图片ID不能为空')
  }
})
</script>

<template>
  <div class="wallpaper-detail-details">
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <!-- 背景图片 -->
    <div 
      v-if="wallpaper.image"
      class="wallpaper-detail-background-image" 
      :style="{ backgroundImage: `url(${wallpaper.image})` }"
    ></div>
    
    <!-- 内容区域 -->
    <div v-if="!loading && wallpaper.image" class="wallpaper-detail-content-overlay">
      <!--图片-->
      <div class="wallpaper-image">
        <img 
          :src="wallpaper.image" 
          :alt="wallpaper.title" 
          @error="handleImageError"
        >
      </div>
      <!-- 壁纸信息 -->
      <div class="wallpaper-info">
        <p class="wallpaper-title">{{ wallpaper.title }}</p>
        <!-- 操作按钮 -->
        <div class="wallpaper-actions">
          <el-button type="primary" @click="enhancedDownload" :loading="downloading">
            <svg t="1754291738718" class="icon" viewBox="0 0 1027 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="10172" width="48" height="48"><path d="M906.81 111.56H719c-19.446 0-36.333 16.888-36.333 36.334s16.887 36.334 36.334 36.334h187.81c24.564 0 44.01 22.005 44.01 48.616V901.18c0 26.611-19.446 48.616-44.01 48.616H117.19c-24.564 0-44.01-22.005-44.01-48.616V233.355c0-26.61 19.446-48.615 44.01-48.615h189.857c19.446 0 36.334-16.888 36.334-36.334s-16.888-36.334-36.334-36.334H117.19C51.175 112.072 0 165.805 0 233.867v668.338C0 968.22 51.175 1024 117.19 1024h792.18c63.456 0 117.189-53.733 117.189-121.795v-668.85C1024 165.293 972.826 111.56 906.811 111.56" fill="#333333" p-id="10173"></path><path d="M305 480.016c-14.84 14.84-14.84 36.334 0 51.174l180.134 180.134 2.558 2.56s2.56 0 2.56 2.558c2.558 2.558 5.117 2.558 7.164 5.117 2.558 0 2.558 0 5.117 2.559 2.559 0 5.117 2.559 9.723 2.559 2.559 0 5.118 0 9.723-2.56 2.559 0 2.559 0 5.118-2.558 2.558 0 5.117-2.559 7.164-5.117 0 0 2.559 0 2.559-2.559l2.559-2.559L719.512 531.19c14.841-14.84 14.841-36.333 0-51.174-14.84-14.84-36.333-14.84-51.174 0L549.102 599.252V36.334C549.102 16.888 532.214 0 512.768 0s-36.334 16.888-36.334 36.334v562.918L357.198 480.016c-13.306-14.84-37.358-14.84-52.198 0" fill="#333333" p-id="10174"></path></svg>
            <p>{{ downloading ? '下载中...' : '下载壁纸' }}</p>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 错误状态 -->
    <div v-if="!loading && !wallpaper.image" class="error-overlay">
      <div class="error-content">
        <h3>加载失败</h3>
        <p>无法获取图片信息，请稍后重试</p>
        <el-button @click="retryLoad">重试</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.wallpaper-detail-details {
  height: 78.5vh;
  position: relative;
  overflow: hidden;

  /* 加载状态 */
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .loading-spinner {
      width: 50px;
      height: 50px;
      border: 3px solid rgba(255, 255, 255, 0.3);
      border-top: 3px solid #fff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 20px;
    }

    p {
      color: #fff;
      font-size: 16px;
    }
  }

  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  /* 错误状态 */
  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .error-content {
      text-align: center;
      color: #fff;

      h3 {
        margin-bottom: 10px;
        font-size: 24px;
      }

      p {
        margin-bottom: 20px;
        font-size: 16px;
        opacity: 0.8;
      }
    }
  }

  /*背景*/
  .wallpaper-detail-background-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    filter: blur(3px);
    transform: scale(1.1);
  }



  /*内容*/
  .wallpaper-detail-content-overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 850px;
    height: 550px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: #555555;
    border-radius: 16px;
    backdrop-filter: blur(10px);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
    z-index: 10;

    .wallpaper-image {
      width: 100%;
      height: 500px;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;
      border-radius: 12px;
      margin-bottom: 20px;
      padding: 0 20px;

      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        border-radius: 12px;
        max-width: 100%;
        max-height: 100%;
      }


    }

    /*壁纸信息*/
    .wallpaper-info {
      width: 100%;
      padding: 0 10px;
      text-align: center;

      /*名称*/
      .wallpaper-title {
        color: #ffffff;
        margin-bottom: 20px;
        font-size: 1rem;
      }

      /*标签*/
      .wallpaper-actions {
        margin-bottom: 10px;
        display: flex;
        justify-content: center;

        :deep(.el-button) {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          padding: 12px 24px;
        }

        svg{
          width: 20px;
          height: 20px;
          margin-right: 10px;
        }

        p{
          margin-top: 3px;
          font-size: 18px;
        }
      }

      /* 缓存状态指示器 */
      .cache-indicator {
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5px;
        padding: 5px 10px;
        background: rgba(46, 204, 113, 0.2);
        border: 1px solid rgba(46, 204, 113, 0.3);
        border-radius: 15px;
        color: #2ecc71;

        .cache-icon {
          font-size: 14px;
        }

        .cache-text {
          font-size: 12px;
          font-weight: 500;
        }
      }


    }
  }
}
</style>